<template>
  <div class="app-container">
    <!-- 页面说明 -->
    <div class="page-header">
      <h3>我的考核任务</h3>
      <p class="page-desc">显示分配给当前用户的考核任务（默认显示今天的任务）</p>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入任务标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务日期" prop="taskDate">
        <el-date-picker
          v-model="queryParams.taskDate"
          type="date"
          placeholder="选择任务日期"
          value-format="yyyy-MM-dd"
          size="small"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['system:assessUser:list']"
        >搜索</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assessUserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务标题" align="center" prop="title" width="200" show-overflow-tooltip />
      <el-table-column label="任务描述" align="center" prop="description" width="250" show-overflow-tooltip />
      <el-table-column label="分数" align="center" prop="fraction" width="80">
        <template slot-scope="scope">
          <span :class="getScoreClass(scope.row.fraction)">{{ scope.row.fraction || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务时间" align="center" prop="taskDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最终分数" align="center" prop="finalScore" width="140">
        <template slot-scope="scope">
          <span :class="getScoreClass(scope.row.finalScore)">{{ formatScore(scope.row.finalScore) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否完成" align="center" prop="isFinish" width="190">
        <template slot-scope="scope">
          <div class="status-container">
            <el-switch
              v-model="scope.row.isFinish"
              :active-value="1"
              :inactive-value="0"
              active-text="已完成"
              inactive-text="未完成"
              active-color="#67C23A"
              inactive-color="#F56C6C"
              :disabled="!rowCanOperate(scope.row)"
              @change="handleStatusChange(scope.row)"
              class="status-switch"
            ></el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-if="scope.row.remark" class="remark-display">
            <div v-for="(remark, index) in parseRemarks(scope.row.remark)" :key="index" class="remark-item">
              <span class="remark-user">{{ remark.userName }}:</span>
              <span class="remark-text">{{ remark.content }}</span>
              <span class="remark-time">{{ formatTime(remark.time) }}</span>
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
    </el-table>

  </div>
</template>

<script>
import { listAssessUser, updateAssessUser } from "@/api/system/assessUser"

export default {
  name: "MyAssessTasks",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 考核任务表格数据
      assessUserList: [],
      // 查询参数
      queryParams: {
        title: null,
        taskDate: this.getTodayDate() // 默认查询今天的任务
      },
      // 当前用户ID
      currentUserId: null
    }
  },
  created() {
    this.currentUserId = this.$store.state.user.id
    // 确保查询参数中的日期是今天的日期
    this.queryParams.taskDate = this.getTodayDate()
    this.getList()
  },
  mounted() {
    this.getList()
  },
  activated() {
    this.getList()
  },
  watch: {
    '$route'(to, from) {
      if (to.path === '/system/assessUser/myTasks') {
        this.getList()
      }
    }
  },
  methods: {
    /** 查询我的考核任务列表 */
    getList() {
      this.loading = true
      // 添加时间戳参数防止缓存
      const params = {
        ...this.queryParams,
        _t: Date.now(),
        userId: this.currentUserId // 只查询当前用户的任务
      }
      listAssessUser(params).then(response => {
        this.assessUserList = response.rows || response.data || []
        this.loading = false
      }).catch(error => {
        this.loading = false
        console.error('获取任务列表失败:', error)
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 重置时设置为今天的日期
      this.queryParams.taskDate = this.getTodayDate()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改完成状态 */
    handleStatusChange(row) {
      const isFinish = row.isFinish
      const id = row.id
      const fraction = row.fraction
      
      let finalScore
      if (isFinish === 1) {
        // 已完成：取当前任务分数
        finalScore = Number(fraction) || 0
      } else {
        // 未完成：0分
        finalScore = 0
      }
      
      const updateData = { 
        id: parseInt(id), 
        isFinish: parseInt(isFinish),
        finalScore: parseFloat(finalScore.toFixed(2))
      }
      
      updateAssessUser(updateData).then(() => {
        // 更新成功后，重新获取数据以获取正确的最终分数
        this.getList()
        this.$modal.msgSuccess("更新成功")
      }).catch(() => {
        // 恢复原状态
        row.isFinish = isFinish === 1 ? 0 : 1
      })
    },
    // 判断行是否可操作
    rowCanOperate(row) {
      return row && (row.operation !== undefined ? row.operation : row.isOperation)
    },
    // 解析备注
    parseRemarks(remarkStr) {
      if (!remarkStr) return []
      try {
        return JSON.parse(remarkStr)
      } catch (e) {
        return []
      }
    },
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      return this.parseTime(timeStr, '{y}-{m}-{d} {h}:{i}:{s}')
    },
    // 分数样式
    getScoreClass(score) {
      return ''
    },
    // 格式化分数显示，保留两位小数
    formatScore(score) {
      if (score === null || score === undefined || score === '') {
        return '-'
      }
      return parseFloat(score).toFixed(2)
    },
    // 获取今天的日期字符串
    getTodayDate() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
  padding: 15px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.page-header h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 18px;
  font-weight: bold;
}

.page-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.status-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.status-switch {
  transform: scale(0.9);
}

.remark-display {
  display: flex;
  flex-direction: column;
  gap: 4px;
  max-height: 100px;
  overflow-y: auto;
}

.remark-item {
  background: #f9fafb;
  border: 1px solid #eef0f2;
  border-radius: 4px;
  padding: 4px 6px;
  font-size: 12px;
}

.remark-user {
  font-weight: 600;
  margin-right: 6px;
  color: #409EFF;
}

.remark-text {
  color: #333;
  margin-right: 6px;
}

.remark-time {
  color: #909399;
  font-size: 10px;
}

</style>
